import api from '@/services/api';

export type AttendanceStatus = 'PRESENT' | 'ABSENT' | 'LEAVE';

export interface StudentAttendanceDetail {
  studentId: number;
  studentNumber: string;
  name: string;
  gender: string;
  status: AttendanceStatus | null;
  attendanceId: number | null;
  remarks: string | null;
}

export interface AttendanceStatistics {
  date: string;
  presentCount: number;
  absentCount: number;
  leaveCount: number;
  totalCount: number;
  presentRate: number;
  absentRate: number;
  leaveRate: number;
}

export interface BatchAttendanceSubmitRequest {
  date: string;
  attendances: {
    studentId: number;
    status: AttendanceStatus;
    remarks?: string;
  }[];
}

export interface PageResponse<T> {
  content: T[];
  totalElements: number;
  totalPages: number;
  size: number;
  number: number;
}

// 缓存机制
interface CacheItem<T> {
  data: T;
  timestamp: number;
}

const cache: {
  todayStats?: CacheItem<AttendanceStatistics>;
  weeklyStats?: CacheItem<AttendanceStatistics[]>;
  detailsByDate: Map<string, CacheItem<StudentAttendanceDetail[]>>;
} = {
  detailsByDate: new Map()
};

// 缓存过期时间（5分钟）
const CACHE_EXPIRY = 5 * 60 * 1000;

// 检查缓存是否有效
const isCacheValid = <T>(cacheItem?: CacheItem<T>): boolean => {
  if (!cacheItem) return false;
  return Date.now() - cacheItem.timestamp < CACHE_EXPIRY;
};

export const attendanceService = {
  // 获取近七天考勤统计
  getLastSevenDaysStats: async (): Promise<AttendanceStatistics[]> => {
    // 检查缓存
    if (isCacheValid(cache.weeklyStats)) {
      return cache.weeklyStats!.data;
    }
    
    try {
      const response = await api.get('/teacher/attendance/stats/last-seven-days');
      const data = response.data || [];
      
      // 更新缓存
      cache.weeklyStats = {
        data,
        timestamp: Date.now()
      };
      
      return data;
    } catch (error) {
      console.error('获取近七天考勤统计失败:', error);
      throw error;
    }
  },

  // 获取今日考勤统计
  getTodayStats: async (): Promise<AttendanceStatistics> => {
    // 检查缓存
    if (isCacheValid(cache.todayStats)) {
      return cache.todayStats!.data;
    }
    
    try {
      const response = await api.get('/teacher/attendance/stats/today');
      const data = response.data;
      
      // 更新缓存
      cache.todayStats = {
        data,
        timestamp: Date.now()
      };
      
      return data;
    } catch (error) {
      console.error('获取今日考勤统计失败:', error);
      throw error;
    }
  },

  // 获取指定日期考勤统计
  getAttendanceStatsByDate: async (date: string): Promise<AttendanceStatistics> => {
    try {
      const response = await api.get(`/teacher/attendance/stats/by-date?date=${date}`);
      return response.data;
    } catch (error) {
      console.error(`获取指定日期(${date})考勤统计失败:`, error);
      throw error;
    }
  },

  // 获取指定日期学生考勤详情
  getAttendanceDetailsByDate: async (date: string): Promise<StudentAttendanceDetail[]> => {
    // 检查缓存
    const cacheKey = date;
    const cachedItem = cache.detailsByDate.get(cacheKey);
    if (isCacheValid(cachedItem)) {
      return cachedItem!.data;
    }
    
    try {
      const response = await api.get(`/teacher/attendance/details/by-date?date=${date}`);
      const data = response.data || [];
      
      // 更新缓存
      cache.detailsByDate.set(cacheKey, {
        data,
        timestamp: Date.now()
      });
      
      return data;
    } catch (error) {
      console.error(`获取指定日期(${date})学生考勤详情失败:`, error);
      throw error;
    }
  },

  // 批量提交学生考勤
  batchSubmitAttendance: async (data: BatchAttendanceSubmitRequest): Promise<number> => {
    try {
      console.log('批量提交考勤API请求:', {
        url: '/teacher/attendance/batch-submit',
        method: 'POST',
        data: JSON.stringify(data, null, 2)
      });
      
      const response = await api.post('/teacher/attendance/batch-submit', data);
      
      console.log('批量提交考勤API响应:', {
        status: response.status,
        statusText: response.statusText,
        data: response.data
      });
      
      // 提交成功后清除相关缓存
      cache.todayStats = undefined;
      cache.detailsByDate.delete(data.date);
      
      return response.data || 0; // 返回成功提交的考勤记录数量
    } catch (error) {
      console.error('批量提交学生考勤失败:', error);
      throw error;
    }
  },

  // 清除缓存
  clearCache: () => {
    cache.todayStats = undefined;
    cache.weeklyStats = undefined;
    cache.detailsByDate.clear();
  },

  // 家长查看学生考勤记录
  getStudentAttendanceForParent: async (params: {
    studentId: number;
    startDate?: string;
    endDate?: string;
  }): Promise<StudentAttendanceDetail[]> => {
    try {
      const { studentId, startDate, endDate } = params;
      let url = `/api/parent/students/${studentId}/attendance`;
      
      if (startDate && endDate) {
        url += `?startDate=${startDate}&endDate=${endDate}`;
      }
      
      const response = await api.get(url);
      return response.data || [];
    } catch (error) {
      console.error(`家长查看学生(${params.studentId})考勤记录失败:`, error);
      throw error;
    }
  },

  // 通用接口：获取学生考勤记录
  getStudentAttendance: async (params: {
    studentId: number;
    startDate?: string;
    endDate?: string;
  }): Promise<StudentAttendanceDetail[]> => {
    try {
      const { studentId, startDate, endDate } = params;
      let url = `/api/${studentId}/attendance`;
      
      if (startDate && endDate) {
        url += `?startDate=${startDate}&endDate=${endDate}`;
      }
      
      const response = await api.get(url);
      return response.data || [];
    } catch (error) {
      console.error(`获取学生(${params.studentId})考勤记录失败:`, error);
      throw error;
    }
  },
};